package com.huangmb.anymark.server.utils;

import sun.misc.BASE64Encoder;

/**
 * 七牛云存储的工具类
 *
 * @author hmb
 * @version 1.0
 * @since 2016/5/17 16:56
 */
public class QiniuUtils {
    private static final String AccessKey = "brBj00fMQ6QDdLebg5MFTwXEnjP8KTRUeO5U3Ayp";
    private static final String AppSecret = "9agptXkPH4HOw90ptE1Snm1jfHJkM0VqBl0ndVn0";

    /**
     * 获得上传凭证
     *
     * @param putPolicy 客户端发来的上传策略
     * @return 生成的上传凭证
     */
    public static String getPutPolicy(String putPolicy) {

        //上传策略
        String encodedPutPolicy = UrlSafeBase64Encode(putPolicy.getBytes());
        //hmacSha1进行签名
        byte[] encryptData = DigestUtils.hmacSha1(encodedPutPolicy, AppSecret);
        //加密签名
        String encodedSign = UrlSafeBase64Encode(encryptData);
        //组成上传凭证
        return AccessKey + ":" + encodedSign + ":" + encodedPutPolicy;
    }

    private static String UrlSafeBase64Encode(byte[] data) {
        String str = new BASE64Encoder().encode(data);
        //根据七牛官网要求，将上传凭证中的"+"改为"-"，将"/"改为"_"，达到URL安全的目的
        str = str.replace("+", "-").replace("/", "_");
        return str;
    }
}
